const ipc = require('electron').ipcRenderer;
const m_path = require('path');
const exec = require('child-process-promise').exec;
const xml = require("xml");
const xmlReader = require("xmlreader");
const fs = require("fs");
//global variable

let OutputUDXType = "zip";

//after choose folder
ipc.on('openFolder-path', function (event, path) {
    if (!path) path = '';
    if (path instanceof Array) {
        let state = isRepeat('method_list', path[0]);
        if (state === false) {
            let item_name = m_path.basename(path[0]);
            addList("method_list", item_name, path[0]);
        }
    }
})

//after choose format file 
ipc.on('openFormatFile-path', function (event, path) {
    if (!path) path = '';
    $("#src-file-path").val(path);
})

//after choose udx file
ipc.on('openUDXFile-path', function (event, path) {
    if (!path) path = '';
    $("#udx-file-path").val(path);
})


//after save to folder
ipc.on('saveToFolder-path', function (event, path) {
    if (!path) path = '';
    if (path === '') return false;
    let selectedItem = getSelectedItem("method_list");

    if (selectedItem.filepath === "") {
        toastr.warning("you must choose a mapping method.", 'Warning', { timeOut: 3000 })
        return false;
    }
    var InputFilePath = $("#udx-file-path").val();
    var OutPutFIlePath = path[0];
    if (InputFilePath === "") {
        toastr.warning("input file can not null.", 'Warning', { timeOut: 3000 });
        return false;
    }

    UnZipFile(InputFilePath, OutPutFIlePath, function (err) {
        if (err !== undefined) {
            toastr.error("UDX to format file error." + err, 'Error', { timeOut: 3000 });
            return false;
        }
        //delete temp file

        fs.exists(OutPutFIlePath + '\\configure.udxcfg', function (exists) {
            if (exists) {
                fs.unlink(OutPutFIlePath + '\\configure.udxcfg', function (err) {
                    if (err) {
                        toastr.error("delete temporary file error." + err, 'Error', { timeOut: 3000 });
                        return console.error(err);
                    }
                });
            }
        })


    })



})
//after save format file
ipc.on('saveFormatFile-path', function (event, path) {
    if (!path) path = '';
    if (path === '') return false;
    let selectedItem = getSelectedItem("method_list");

    if (selectedItem.filepath === "") {
        toastr.warning("you must choose a mapping method.", 'Warning', { timeOut: 3000 })
        return false;
    }

    var InputFilePath = $("#udx-file-path").val();
    var OutPutFIlePath = path;
    if (InputFilePath === "") {
        toastr.warning("input file can not null.", 'Warning', { timeOut: 3000 })
        return false;
    }
    if (OutPutFIlePath === "") {
        toastr.warning("output file can not null.", 'Warning', { timeOut: 3000 })
        return false;
    }
    // var MethodPath= "E:\\Kuner\\work\\Schema_Udx_Helper\\now\\AMPHA\\vge.jar";
    // var InputFilePath="E:\\Kuner\\work\\FVCOM_All\\step3\\AMPHA_obc.dat";
    // var OutPutFIlePath = "C:\\Users\\Administrator\\Desktop\\c.xml";

    //读取文件获取type,start
    fs.readFile(selectedItem.filepath + "\\cfg.xml", function (err, data) {
        if (err) {
            $("#log-area").text('error:\n' + err);
            return console.error(err);
        }
        xmlReader.read(data.toString(), function (errors, response) {
            if (null !== errors) {
                $("#log-area").text('error:\n' + errors);
                return console.error(errors);
            }
            console.log(response);
            if (response !== undefined
                && response.config !== undefined
                && response.config.type !== undefined
                && response.config.start !== undefined
            ) {
                var MethodPath = selectedItem.filepath + "\\" + response.config.start.text();
                var mType = response.config.type.text();
                runU2F(MethodPath, InputFilePath, OutPutFIlePath, mType);
            } else {
                $("#log-area").text('error:\nThis mapping method is not correct.Please check cfg.xml');
                return false;
            }
        });

    });



})

//after save UDX file
ipc.on('saveUDXFile-path', function (event, path) {
    if (!path) path = '';
    if (path === '') return false;
    let selectedItem = getSelectedItem("method_list");

    if (selectedItem.filepath === "") {
        toastr.error("you must choose a mapping method.", 'Error', { timeOut: 3000 })
        return false;
    }



    var InputFilePath = $("#src-file-path").val();
    var OutPutFIlePath = path;
    if (InputFilePath === "") {
        toastr.warning("input file can not null.", 'Warning', { timeOut: 3000 })
        return false;
    }
    if (OutPutFIlePath === "") {
        toastr.warning("output file can not null.", 'Warning', { timeOut: 3000 })
        return false;
    }
    // var MethodPath= "E:\\Kuner\\work\\Schema_Udx_Helper\\now\\AMPHA\\vge.jar";
    // var InputFilePath="E:\\Kuner\\work\\FVCOM_All\\step3\\AMPHA_obc.dat";
    // var OutPutFIlePath = "C:\\Users\\Administrator\\Desktop\\c.xml";

    //读取文件获取type,start
    fs.readFile(selectedItem.filepath + "\\cfg.xml", function (err, data) {
        if (err) {
            $("#log-area").text('error:\n' + err);
            return console.error(err);
        }
        xmlReader.read(data.toString(), function (errors, response) {
            if (null !== errors) {
                $("#log-area").text('error:\n' + errors);
                return console.error(errors);
            }
            console.log(response);
            if (response !== undefined
                && response.config !== undefined
                && response.config.type !== undefined
                && response.config.start !== undefined
            ) {
                var MethodPath = selectedItem.filepath + "\\" + response.config.start.text();
                var mType = response.config.type.text();
                runF2U(MethodPath, InputFilePath, OutPutFIlePath, mType);
            } else {
                $("#log-area").text('error:\nThis mapping method is not correct.Please check cfg.xml');
                return false;
            }
        });

    });


})

//save zip UDX 
ipc.on('saveZipUdx-path', function (event, path) {
    if (!path) path = '';
    if (path === '') return false;
    let selectedItem = getSelectedItem("method_list");
    if (selectedItem.filepath === "") {
        toastr.warning("you must choose a mapping method.", 'Warning', { timeOut: 3000 })
        return false;
    }
    var inputFilePath = $("#src-file-path").val();

    if (inputFilePath === undefined || inputFilePath === "") {
        toastr.warning("you must choose file to map.", 'Warning', { timeOut: 3000 })
        return false;
    }
    var mName = PathUtil.getNameWithoutExtension(inputFilePath);
    var mDirectory = PathUtil.getDirectory(inputFilePath);
    var mFileArray = new Array();

    //get fileList
    fs.readdir(mDirectory, function (err, files) {

        if (err !== null) {
            toastr.error('read directory error.' + err, 'Error', { timeOut: 3000 });
            return;
        }
        mFileArray.push(inputFilePath);
        files.forEach(function (value, index, array) {
            var TempName = PathUtil.getNameWithoutExtension(value);
            if (mName === TempName) {
                if (PathUtil.getName(value) !== PathUtil.getName(inputFilePath)) {
                    mFileArray.push(mDirectory + "\\" + value);
                }
            }

        });

        //configure.udxcfg
        var stream = getConfig(mFileArray);

        fs.writeFile(mDirectory + '\\configure.udxcfg', stream, function (err) {
            if (err) {
                return console.error(err);
            }
            //add list
            mFileArray.push(mDirectory + '\\configure.udxcfg');
            //zip
            ZipFile(mFileArray, path, function (err) {
                if (err !== undefined) return;
                //delete temp file
                fs.unlink(mDirectory + '\\configure.udxcfg', function (err) {
                    if (err) {
                        return console.error(err);
                    }
                });
            });
        });
    })
})



function _bindClick() {

    //choose method folder
    $("#open_file").on("click", function () {
        ipc.send('openFolder-dialog');
    });

    //choose format file
    $("#ChooseSrcFile").on("click", function () {
        ipc.send('openFormatFile-dialog');
    });

    //choose udx file
    $("#ChooseUdxFile").on("click", function () {
        ipc.send('openUDXFile-dialog');
    });

    //show udx to format file 
    $("#Run_U2F").on('click', function (event) {
        let selectedItem = getSelectedItem("method_list");

        if (selectedItem.filepath === "") {
            toastr.warning("you must choose a mapping method.", 'Warning', { timeOut: 3000 })
            return false;
        }


        var MethodPath = selectedItem.filepath + "\\vge.jar";
        var InputFilePath = $("#input-udx-file").val();
        var OutPutFIlePath = $("#output-format-file").val();
        if (InputFilePath === "") {
            toastr.warning("input file can not null.", 'Warning', { timeOut: 3000 })
            return false;
        }
        if (OutPutFIlePath === "") {
            toastr.warning("output file can not null.", 'Warning', { timeOut: 3000 })
            return false;
        }
        // var MethodPath= "E:\\Kuner\\work\\Schema_Udx_Helper\\now\\AMPHA\\vge.jar";
        // var InputFilePath="E:\\Kuner\\work\\FVCOM_All\\step3\\AMPHA_obc.dat";
        // var OutPutFIlePath = "C:\\Users\\Administrator\\Desktop\\c.xml";
        runU2F(MethodPath, InputFilePath, OutPutFIlePath, 'jar');

    })

    //delete
    
    $("#delete").on('click',function(){
        removeActive("method_list");
    })

    //bind btn group
    $(".custom-btn-group span").on('click', function () {
        var Btns = $(this)[0]['parentNode']['children'];

        $(Btns).each(function () {
            if ($(this).hasClass("active")) {
                $(this).removeClass("active");
            }
        })

        $(this).addClass('active');
        OutputUDXType = $(this).attr('value');
    })

    //ok clicked
    $("#src2udx_ok").on("click", function () {
        var inputFilePath = $("#src-file-path").val();
        if (inputFilePath === "" || inputFilePath === undefined) {
            toastr.warning("File not selected", 'Warning', { timeOut: 3000 });
            return false;
        }
        let selectedItem = getSelectedItem("method_list");
        if (selectedItem.filepath === "") {
            toastr.warning("you must choose a mapping method.", 'Warning', { timeOut: 3000 })
            return false;
        }
        if (OutputUDXType === "zip") {
            ipc.send('saveZipUdx-dialog');
        } else {
            ipc.send('saveUDXFile-dialog');
        }
    });

    //udx2src_ok
    $("#udx2src_ok").on("click", function () {
        var inputFilePath = $("#udx-file-path").val();
        if (inputFilePath === "" || inputFilePath === undefined) {
            toastr.warning("File not selected", 'Warning', { timeOut: 3000 });
            return false;
        }
        let selectedItem = getSelectedItem("method_list");
        if (selectedItem.filepath === "") {
            toastr.warning("you must choose a mapping method.", 'Warning', { timeOut: 3000 });
            return false;
        }

        //input udx is zip or xml
        if ( m_path.extname(inputFilePath)===".zip") {
            ipc.send('saveToFolder-dialog');
        } else if ( m_path.extname(inputFilePath)===".xml") {
            ipc.send('saveFormatFile-dialog');
        } else {
            toastr.warning("Unknown input file.", 'Warning', { timeOut: 3000 });
            return false;
        }
    });



}


function getConfig(_FilesPathList) {
    if (_FilesPathList === undefined || _FilesPathList.length <= 0) {
        toastr.warning('no file to zip.', 'Warning', { timeOut: 3000 });
        return;
    }

    var AddArray = new Array();

    var FileCount = _FilesPathList.length;
    AddArray.push({ _attr: { count: FileCount } });

    for (var i = 0; i < FileCount; i++) {

        var currentName = PathUtil.getName(_FilesPathList[i]);
        var OneFile = {
            Add: [{ _attr: { value: currentName } }]
        }
        AddArray.push(OneFile);
    }


    var rslt = [{
        UDXZip: [{
            FileName: AddArray
        }]
    }]
    var Rslt = xml(rslt, true);
    return Rslt;

}

function ZipFile(_FilesPathList, _zipFilePath, callBack) {
    if (_FilesPathList === undefined || _FilesPathList.length <= 0) {
        toastr.warning('no file to zip.', 'Warning', { timeOut: 3000 });
        return;
    }
    var winRarPath = PathUtil.getDirectory(__dirname) + "\\lib\\winrar\\WinRAR.exe";

    let m_command = winRarPath;
    m_command += " a -ep1 -r -m3 -afzip -ibck " + _zipFilePath;

    for (var i = 0; i < _FilesPathList.length; i++) {
        m_command += " " + _FilesPathList[i];
    }
    exec(m_command).then(function (result) {
        var stdout = result.stdout;
        var stderr = result.stderr;
        if (stdout !== '') {
            $("#log-area").text('stdout:\n' + stdout);
        }
        if (stderr != '') {
            $("#log-area").text('stdout:\n' + stderr);
        } else {
            toastr.info("Mapping completed.", 'Information', { timeOut: 3000 });
            callBack(undefined);
        }
    }).catch(function (err) {
        toastr.error('Mapping error.', 'Error', { timeOut: 3000 });
        $("#log-area").text('Error:\n' + err);
        callBack(err);
    });

}

function UnZipFile(ZipFilePath, DestDirectory, callBack) {
    if (ZipFilePath === undefined ||
        ZipFilePath === "" ||
        DestDirectory === undefined ||
        DestDirectory === "") {
        return false;
    }
    var winRarPath = PathUtil.getDirectory(__dirname) + "\\lib\\winrar\\WinRAR.exe";

    let m_command = m_path.normalize(winRarPath);
    m_command += " e -y -ibck " + m_path.normalize(ZipFilePath) + " " + m_path.normalize(DestDirectory);
    exec(m_command).then(function (result) {
        var stdout = result.stdout;
        var stderr = result.stderr;
        if (stdout !== '') {
            $("#log-area").text('stdout:\n' + stdout);
        }
        if (stderr != '') {
            $("#log-area").text('stdout:\n' + stderr);
        } else {
            toastr.info("Mapping completed.", 'Information', { timeOut: 3000 });
            callBack(undefined);
        }
    }).catch(function (err) {
        toastr.error('Mapping error.', 'Error', { timeOut: 3000 });
        $("#log-area").text('Error:\n' + err);
        callBack(err);
    });

}

function runF2U(_MethodPath, _InputFilePath, _OutputFilePath, _type) {
    let m_command = "";
    if (_type === 'exe') {
        m_command += '"' + _MethodPath;
        m_command += '" -r -f "' + _InputFilePath;
        m_command += '" -u "' + _OutputFilePath + '"';
    } else if (_type === 'jar') {
        m_command += 'java -jar "' + _MethodPath;
        m_command += '" -r -f "' + _InputFilePath;
        m_command += '" -u "' + _OutputFilePath + '"';
    } else {
        toastr.error('unknown mapping method type.', 'Error', { timeOut: 3000 });
        return false;
    }
    exec(m_command).then(function (result) {
        var stdout = result.stdout;
        var stderr = result.stderr;
        if (stdout !== '') {
            $("#log-area").text('stdout:\n' + stdout);
        }
        if (stderr != '') {
            $("#log-area").text('stdout:\n' + stderr);
        } else {
            toastr.info("Mapping completed.", 'Information', { timeOut: 3000 });
        }
    }).catch(function (err) {
        toastr.error('Mapping error.', 'Error', { timeOut: 3000 });
        $("#log-area").text('Error:\n' + err);
    });
}

function runU2F(_MethodPath, _InputFilePath, _OutputFilePath, _type) {
    let m_command = "";
    if (_type === 'exe') {
        m_command += '"' + _MethodPath;
        m_command += '" -w -u "' + _InputFilePath;
        m_command += '" -f "' + _OutputFilePath + '"';
    } else if (_type === 'jar') {
        m_command += 'java -jar "' + _MethodPath;
        m_command += '" -w -u "' + _InputFilePath;
        m_command += '" -f "' + _OutputFilePath + '"';
    } else {
        toastr.error('unknown mapping method type.', 'Error', { timeOut: 3000 });
        return false;
    }
    exec(m_command).then(function (result) {
        var stdout = result.stdout;
        var stderr = result.stderr;
        if (stdout !== '') {
            $("#log-area").text('stdout:\n' + stdout);
        }
        if (stderr != '') {
            $("#log-area").text('stdout:\n' + stderr);
        } else {
            toastr.info("Mapping completed.", 'Information', { timeOut: 3000 });
        }
    }).catch(function (err) {
        toastr.error('Mapping error.', 'Error', { timeOut: 3000 });
        $("#log-area").text('Error:\n' + err);
    });
}

$(function () {
    bindContextMenu("method_list", "contextMenu");
    _bindClick();
})